package com.link.base.base.accnt.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.dao.mybatis.mapper.AcctAddressMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.model.AcctAddress;
import com.link.base.base.cmqres.model.CmqRes;
import com.link.base.base.cmqres.service.CmqResService;
import com.link.base.core.RSAUtils.SecretKeyUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.mq.util.MqUtil;
import com.link.core.util.StringUtils;
import com.link.core.cllog.LCLogger;
import javax.annotation.Resource;

import com.link.core.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 客户地址service实现类
 *
 * @author  unknwon
 * @date:   2018/11/7 16:44
 * @version 1.0
 */

@Service
public class AcctAddressServiceImpl extends BasicServiceImpl<AcctAddress> implements AcctAddressService {
    private static final Logger logger = LogManager.getLogger(AcctAddressServiceImpl.class);

    private static final String DEFAULT_ADDRESS = "Y";
    private static final String NOT_DEFAULT_ADDRESS = "N";
    /**DMP消费者保存接口URL*/
    private static final String DMP_ADDRESS_INTERFACE_URL = "/link/cdcPubAddress/upsert";

    @Resource
    private AcctAddressMapper acctAddressMapper;

    @Resource
    private CmqResService cmqResService;

    @Resource
    private AccountMapper accountMapper;

    /**
     * 在删除地址之后，触发cmq发送逻辑，获取对象信息 HuangLJ 2017年12月28日
     */
    private AcctAddress acctAddress;

    /**
     * 消息信息
     */
    private String messageInfo = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";

    @Override
    public BasicMapper<AcctAddress> getBasicMapper() throws Exception {

        return acctAddressMapper;
    }

    /**
     * 设置主要默认地址
     *
     * @param address
     */
    @Override
    public void defaultAddrUpdate(AcctAddress address) {
        acctAddressMapper.defaultAddrUpdate(address);

        Long accntId = address.getAcctId();
        Account account = new Account();
        account.setId(accntId);
        // 发送cmq
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList;
        try {
            cmqResList = cmqResService.queryAll(cmqRes);
            if (cmqResList != null && cmqResList.size() > 0) {
                Account accountFull = accountMapper.queryById(account);
                String type = accountFull.getAcctType();
                String message1 = "";
                //经销商
                String dealer = "DEALER1";
                //仓库
                String store = "STORE";
                if (dealer.equals(type)) {
                    message1 = "AccountSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                } else if (store.equals(type)) {
                    message1 = "StoreSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                } else {
                    return;
                }
                String message2 = "\"}";
                String message = message1 + accountFull.getId() + message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName, message);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 设置地址是否有效
     *
     * @param address
     */
    @Override
    public void effectiveAddrUpdate(AcctAddress address) {

        acctAddressMapper.effectiveAddrUpdate(address);
    }

    /**
     * 插入数据后进行操作
     *
     * @param address
     * @throws Exception
     */
    @Override
    public void afterInsert(AcctAddress address) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = address.getAcctId();
                if (accntId != null) {
                    String message2 = "\"}";
                    String message = messageInfo + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     * 更新数据后进行操作
     *
     * @param address
     * @throws Exception
     */
    @Override
    public void afterUpdate(AcctAddress address) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = address.getAcctId();
                if (accntId != null) {
                    String message2 = "\"}";
                    String message = messageInfo + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     *删除数据前的操作
     *
     * @param address
     * @throws Exception
     */
    @Override
    public void beforDelete(AcctAddress address) throws Exception {
        //在删除地址之后，触发cmq发送逻辑，获取对象信息 HuangLJ 2017年12月28日
        acctAddress = this.queryById(address);
    }

    /**
     * 删除后发送消息到cmq
     *
     * @param address
     * @throws Exception
     */
    @Override
    public void afterDelete(AcctAddress address) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Long accntId = acctAddress.getAcctId();
                if (accntId != null) {
                    String message2 = "\"}";
                    String message = messageInfo + accntId + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     * 设置默认地址
     *
     * @author 李宗庭
     * 2017年3月31日
     */
    @Override
    public void setMainAddr(AcctAddress record) throws Exception {
        if (null != record.getAcctId()) {
            AcctAddress newRecord = new AcctAddress();
            newRecord.setAcctId(record.getAcctId());
            List<AcctAddress> list = super.queryAll(newRecord);
            if (list != null && list.size() > 0) {
                for (AcctAddress qdAddr : list) {
                    if (qdAddr.getId().equals(record.getId())) {
                        record.setIsDefault("Y");
                        acctAddressMapper.update(record);
                        Account qa = new Account();
                        qa.setId(record.getAcctId());
                        qa = accountMapper.queryById(qa);
                        // 客户存在
                        if (qa != null) {
                            qa.setAcctAddressId(record.getId());
                            qa.setAddress(record.getAddr());
                            qa.setDistrict(record.getDistrict());
                            qa.setProvince(record.getProvince());
                            qa.setCity(record.getCity());
                            accountMapper.update(qa);
                        }

                    } else {
                        if ("Y".equals(qdAddr.getIsDefault())) {
                            qdAddr.setIsDefault("N");
                            acctAddressMapper.update(qdAddr);
                        }

                    }
                }
            }

        } else {
            throw new ServiceException("ACCT-015");
        }
    }


    /**
     * 新建地址
     *
     * @author 李宗庭
     * 2017年4月13日
     */
    @Override
    public void insert(AcctAddress record) throws Exception {
        if (GUIDE_APP.equals(record.getLoginType())) {
            record.setIsEffective(DEFAULT_ADDRESS);
            String isDefault = record.getIsDefault();
            if (StringUtils.isNull(isDefault) || NOT_DEFAULT_ADDRESS.equals(isDefault)) {
                record.setIsDefault(NOT_DEFAULT_ADDRESS);
            }
            super.insert(record);
            String flag = "Y";
            if (flag.equals(record.getSetmainFlag())) {
                record = acctAddressMapper.queryById(record);
                setMainAddr(record);
            }
        } else {
            super.insert(record);
        }
    }

    /**
     * 重写更新方法，除了正常更新意外，如果判断登录类型为导购且标识为主要，则查询客户地址并将其写入对象主地址字段
     *
     * @param record
     * @throws Exception
     */
    @Override
    public void update(AcctAddress record) throws Exception {
        super.update(record);
        String flag = "Y";
        if (GUIDE_APP.equals(record.getLoginType())) {
            if (flag.equals(record.getSetmainFlag())) {
                record = acctAddressMapper.queryById(record);
                setMainAddr(record);
            }
        }
    }

    /**
     * 将地址数据推送至DMP,由DMP调用本服务器中upsert方法
     *
     * @author 宁蓝昊
     * @date 2019-04-02 16:26
     * @param record
     * @throws Exception
     */
    @Override
    public void saveToDmp(AcctAddress record) throws Exception {
        String dmpAddressUrl = "http://"
                + "127.0.0.1:8003/dmp" + DMP_ADDRESS_INTERFACE_URL;
        Map<String, Object> param = new HashMap<>(16);
        CoreUser user = UserUtil.getUser();
        param.put("id", record.getId());
        param.put("row_status", record.getRow_status());
        param.put("dataSource", "MarketingPlatform");
        param.put("orgId", user.getOrgId());
        param.put("postnId", user.getPostnId());
        param.put("dataType", "Address");
        SecretKeyUtil.DmpParamUtil.transformDmpAnnotationField(record, param);
        JSONObject paramJson = JSONObject.parseObject(JSONObject.toJSONString(param));
        logger.info("Base [消费者地址]传入接口参数：" + paramJson.toString());
        Map<String, Object> result = SecretKeyUtil.dmpHttpPostWithDefault(dmpAddressUrl, paramJson);
        logger.info("DMP [消费者地址]返回数据：" + result.toString());
        JSONObject message = null;
        try {
            message = JSONObject.parseObject(result.get("message").toString());
        } catch (Exception e) {
            throw new BasicServiceException("DMP系统连接失败，当前URL为【" + dmpAddressUrl + "】");
        }
        boolean requestFail = !(boolean) result.get("success") || !(boolean) message.get("success");
        if (requestFail) {
            throw new BasicServiceException("DMP系统新建消费者地址失败");
        }
    }
}
